package com.maint.m

import android.annotation.SuppressLint
import android.content.Intent
import android.os.Bundle
import android.util.Log
import android.view.View
import android.widget.Button
import android.widget.TextView
import android.widget.Toast
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.maint.m.data.model.OperationItem
import com.google.gson.Gson
import okio.ByteString
import org.json.JSONObject
import org.json.JSONArray
import kotlin.math.log

class TicketConfirmationActivity : BaseActivity(), WebSocketMessageListener {

    private lateinit var recyclerView: RecyclerView
    private lateinit var adapter: TicketDetailAdapter
    private var isConnected = false

    private var stationName = "科技城"
    private var unit = ""
    private var dispatchOrderNumber = ""
    private var serialNumber = ""
    private var operationTask = ""
    private var operationItem = mutableListOf<String>()

    // 添加标志位防止重复执行
    private var isSaving = false

    // 跳转来源
    private var source: String? = null

    private val TAG = "TicketConfirmation::"

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        try {
            setContentView(R.layout.activity_ticket_confirmation)
            
            // 获取跳转来源
            source = intent.getStringExtra("source")

            WebSocketManager.getInstance().registerMessageListener(this)

            // 设置标题栏文字
            setToolbarTitle("操作票确认")

            // 启用返回按钮
            supportActionBar?.setDisplayHomeAsUpEnabled(true)

            // 初始化 RecyclerView
            initRecyclerView()

            // 获取传递的数据
            val ticketItem = intent.getSerializableExtra("ticket_item") as? TicketItem
            val websocketData = intent.getStringExtra("websocket_data")

            Log.e("TicketConfirmation", "获取到的票务信息: $websocketData")

            if (ticketItem != null) {
                // 先显示基本信息
                bindBasicInfo(ticketItem)

                // 获取详细信息
                loadTicketDetail(ticketItem.id)
            } else if (websocketData != null) {
                // 显示 WebSocket 数据
                displayWebsocketData(websocketData)
            } else {
                showError("未获取到票务信息")
            }

            // 初始化确认按钮
            initButtons()

        } catch (e: Exception) {
            Log.e("TicketConfirmation", "OnCreate异常", e)
            showError("页面初始化失败: ${e.message}")
        }
    }

    private fun initRecyclerView() {
        try {
            recyclerView = findViewById(R.id.rvOperationItems)
            recyclerView.layoutManager = LinearLayoutManager(this)
            adapter = TicketDetailAdapter(emptyList())
            recyclerView.adapter = adapter
        } catch (e: Exception) {
            Log.e("TicketConfirmation", "RecyclerView初始化失败", e)
            throw e
        }
    }

    private fun bindBasicInfo(ticketItem: TicketItem) {
        val dispatchOrderNumberText = findViewById<TextView>(R.id.tvDetailDispatchOrderNumber)
        val unitText = findViewById<TextView>(R.id.tvDetailUnit)
        val serialNumberText = findViewById<TextView>(R.id.tvDetailSerialNumber)
        val operationTaskText = findViewById<TextView>(R.id.tvDetailOperationTask)

        dispatchOrderNumberText.text = ticketItem.dispatchOrderNumber ?: ""
        unitText.text = ticketItem.unit ?: ""
        serialNumberText.text = ticketItem.serialNumber ?: ""
        operationTaskText.text = ticketItem.operationTask ?: ""
    }

    private fun loadTicketDetail(ticketId: String) {
        Log.d("TicketConfirmation", "开始加载详情数据，ticketId: $ticketId")

        val apiService = NetworkUtils.createService(TicketApiService::class.java)
        val call = apiService.getTicketDetail(TicketDetailRequest(ticketId))

        call.enqueue(object : retrofit2.Callback<TicketDetailResponse> {
            override fun onResponse(
                call: retrofit2.Call<TicketDetailResponse>,
                response: retrofit2.Response<TicketDetailResponse>
            ) {
                Log.d("TicketConfirmation", "网络请求响应: ${response.isSuccessful}")

                if (response.isSuccessful && response.body()?.statusCode == "200") {
                    val result = response.body()?.result
                    Log.d("TicketConfirmation", "获取到详情数据: $result")

                    if (result != null) {
                        bindDetailInfo(result)
                    } else {
                        showError("详情数据为空")
                    }
                } else {
                    showError("获取详情失败: ${response.body()?.message ?: response.message()}")
                }
            }

            override fun onFailure(call: retrofit2.Call<TicketDetailResponse>, t: Throwable) {
                Log.e("TicketConfirmation", "网络请求失败", t)
                showError("网络错误: ${t.message}")
            }
        })
    }

    private fun bindDetailInfo(detail: TicketDetail) {
        try {
            // 显示基本信息
            val dispatchOrderNumberText = findViewById<TextView>(R.id.tvDetailDispatchOrderNumber)
            val unitText = findViewById<TextView>(R.id.tvDetailUnit)
            val serialNumberText = findViewById<TextView>(R.id.tvDetailSerialNumber)
            val operationTaskText = findViewById<TextView>(R.id.tvDetailOperationTask)

            dispatchOrderNumberText.text = detail.dispatchOrderNumber ?: ""
            unitText.text = detail.unit ?: ""
            serialNumberText.text = detail.serialNumber ?: ""
            operationTaskText.text = detail.operationTask ?: ""

            // 更新操作项目列表
            if (::recyclerView.isInitialized && ::adapter.isInitialized) {
                // 将String列表转换为OperationItem列表
                val operationItems = detail.operationItem.mapIndexed { index, content ->
                    OperationItem().apply {
                        number = index + 1
                        this.content = content
                    }
                }
                adapter = TicketDetailAdapter(operationItems)
                recyclerView.adapter = adapter
            }
        } catch (e: Exception) {
            showError("数据显示异常: ${e.message}")
        }
    }

    private fun displayWebsocketData(data: String) {
        try {
            val jsonObject = JSONObject(data)
            unit = jsonObject.optString("unit", "")
            // 优先尝试驼峰命名法(dispatchOrderNumber)，如果不存在则尝试下划线命名法(dispatch_order_number)
            dispatchOrderNumber = jsonObject.optString("dispatchOrderNumber", "").ifEmpty {
                jsonObject.optString("dispatch_order_number", "")
            }
            // 优先尝试驼峰命名法(serialNumber)，如果不存在则尝试下划线命名法(serial_number)
            serialNumber = jsonObject.optString("serialNumber", "").ifEmpty {
                jsonObject.optString("serial_number", "")
            }
            // 优先尝试驼峰命名法(operationTask)，如果不存在则尝试下划线命名法(operation_task)
            operationTask = jsonObject.optString("operationTask", "").ifEmpty {
                jsonObject.optString("operation_task", "")
            }
            // 优先尝试驼峰命名法(operationItem)，如果不存在则尝试下划线命名法(operation_item)
            val operationItems = try {
                jsonObject.optJSONArray("operationItem") ?: jsonObject.optJSONArray("operation_item")
            } catch (e: Exception) {
                null
            }

            // 显示基本信息
            bindBasicInfoFromJson(unit, dispatchOrderNumber, serialNumber, operationTask)

            // 显示操作项目列表
            if (operationItems != null) {
                bindOperationItems(operationItems)
            } else {
                Log.w("TicketConfirmation", "操作项目列表为空或格式不正确")
                // 可以在这里添加一个空的操作项目列表，或者显示一个提示信息
                bindOperationItems(JSONArray()) // 传入空的JSONArray以避免空指针异常
            }

        } catch (e: Exception) {
            Log.e("TicketConfirmation", "解析WebSocket数据失败", e)
        }
    }

    private fun bindBasicInfoFromJson(unit: String, dispatchOrderNumber: String,
                                      serialNumber: String, operationTask: String) {
        val dispatchOrderNumberText = findViewById<TextView>(R.id.tvDetailDispatchOrderNumber)
        val unitText = findViewById<TextView>(R.id.tvDetailUnit)
        val serialNumberText = findViewById<TextView>(R.id.tvDetailSerialNumber)
        val operationTaskText = findViewById<TextView>(R.id.tvDetailOperationTask)

        dispatchOrderNumberText?.text = dispatchOrderNumber
        unitText?.text = unit
        serialNumberText?.text = serialNumber
        operationTaskText?.text = operationTask
    }

    private fun bindOperationItems(operationItems: JSONArray) {
        try {
            operationItem.clear()
            val items = mutableListOf<String>()
            for (i in 0 until operationItems.length()) {
                val item = operationItems.getString(i)
                items.add(operationItems.getString(i))
                operationItem.add(item)
            }

            if (::recyclerView.isInitialized && ::adapter.isInitialized) {
                // 将String列表转换为OperationItem列表
                val operationItems = items.mapIndexed { index, content ->
                    OperationItem().apply {
                        number = index + 1
                        this.content = content
                    }
                }
                adapter = TicketDetailAdapter(operationItems)
                recyclerView.adapter = adapter
            }
        } catch (e: Exception) {
            Log.e("TicketConfirmation", "绑定操作项目失败", e)
        }
    }

    private fun initButtons() {
        try {
            val cancelButton = findViewById<TextView>(R.id.btnCancel)
            val confirmButton = findViewById<TextView>(R.id.btnConfirm)

            cancelButton.setOnClickListener {
                if (source == "photo") {
                    finish()
                } else {
                    // 处理取消操作，返回到StreamingActivity
                    val intent = Intent(this@TicketConfirmationActivity, StreamingActivity::class.java)
                    intent.flags = Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_SINGLE_TOP
                    startActivity(intent)
                    finish()
                }
            }

            confirmButton.setOnClickListener {
                // 处理确认操作
                if (source == "photo") {
                    handleAddTicket()
                } else {
                    val messageMap = mapOf(
                        "business" to 11,
                        "instruct" to 1
                    )
                    val message = Gson().toJson(messageMap)
                    WebSocketManager.getInstance().sendMessage(message)
                }
            }
        } catch (e: Exception) {
            Log.e(TAG, "按钮初始化失败", e)
        }
    }

    private fun showError(message: String) {
        Toast.makeText(this, message, Toast.LENGTH_SHORT).show()
    }

    private fun handleAddTicket() {
        // 防止重复执行
        if (isSaving) {
            Log.w("TicketConfirmation", "保存操作已在进行中，跳过重复执行")
            return
        }

        isSaving = true

        val apiService = NetworkUtils.createService(TicketApiService::class.java)
        Log.i("TicketConfirmation", "新增操作票请求参数:$stationName, $unit, $dispatchOrderNumber, $serialNumber, $operationTask, $operationItem")
        val call = apiService.saveTicket(SaveRequest(stationName,unit,dispatchOrderNumber,serialNumber,operationTask,operationItem))

        call.enqueue(object : retrofit2.Callback<SaveTicketResponse> {
            override fun onResponse(
                call: retrofit2.Call<SaveTicketResponse>,
                response: retrofit2.Response<SaveTicketResponse>
            ) {
                if (response.isSuccessful && response.body()?.statusCode == "200") {
                    Log.d("TicketConfirmation", "新增操作票成功")
                    // 添加刷新标志，返回到TicketListActivity时自动刷新数据
                    val intent = Intent(this@TicketConfirmationActivity, TicketListActivity::class.java)
                    intent.putExtra("NEED_REFRESH", true)
                    intent.flags = Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_SINGLE_TOP
                    startActivity(intent)
                    finish()
                } else {
                    showError("新增操作票失败: ${response.body()?.message ?: response.message()}")
                }
            }

            override fun onFailure(call: retrofit2.Call<SaveTicketResponse>, t: Throwable) {
                Log.e("TicketConfirmation", "网络请求失败", t)
                showError("网络错误: ${t.message}")
            }
        })
    }

    override fun onSupportNavigateUp(): Boolean {
        onBackPressed()
        return true
    }

    override fun onMessageReceived(message: String) {
        // 在UI线程中显示接收到的消息
        runOnUiThread {
            try {
                Toast.makeText(this, "收到消息: $message", Toast.LENGTH_LONG).show()
                // 解析后端返回的 JSON 消息
                val jsonObject = JSONObject(message)
                val business = jsonObject.getInt("business")
                val data = jsonObject.getString("data")

                if (business == 0 && data == "ok") {
                    handleAddTicket()
                }
            } catch (e: Exception) {
                Log.e("WebSocket", "解析消息失败: ${e.message}")
            }
        }
    }

    override fun onBinaryMessageReceived(bytes: ByteString) {
        // 二进制消息处理
        Log.d("WebSocket", "收到二进制消息，长度: ${bytes.size}")
    }

    override fun onConnectionOpened() {
        Log.d("WebSocket", "连接已打开")
    }

    override fun onConnectionFailed(t: Throwable) {
        Log.e("WebSocket", "连接失败: ${t.message}", t)
    }

    override fun onConnectionClosed(code: Int, reason: String) {
        Log.d("WebSocket", "连接已关闭: $code, $reason")
    }

    override fun onDestroy() {
        super.onDestroy()
        // 移除 WebSocket 消息监听器
        WebSocketManager.getInstance().unregisterMessageListener(this)
    }
}
